package com.ruyuan.common.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.PropertyKey;

import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author xx
 */
@Data
public class ErrorCode {

    private static final Map<String, String> CODE_MAP = new HashMap<>();

    private String code;

    private String msg;

    static {
        try {
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("messages.properties");
            while (resources.hasMoreElements()) {
                URL messageUrl = resources.nextElement();
                Properties properties = new Properties();
                InputStream inputStream = messageUrl.openStream();
                try {
                    properties.load(inputStream);
                    properties.stringPropertyNames().forEach(key -> {
                        CODE_MAP.put(key, properties.getProperty(key));
                    });
                } finally {
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ErrorCode code(@PropertyKey(resourceBundle = "messages") String code, Object... params) {
        ErrorCode errorCode = new ErrorCode();
        errorCode.setCode(code);
        String message = CODE_MAP.get(code);
        if (StringUtils.isNotBlank(message)) {
            errorCode.setMsg(MessageFormat.format(message, params));
        } else {
            errorCode.setMsg("");
        }
        return errorCode;
    }

}
